from __future__ import with_statement

try:
    import json
except ImportError:
    import simplejson as json
import os.path

class UserPrefs(dict):
    """
    User preferences.  A dictionary, plus load(), save(), and set(*args)
    methods.
    """

    def __init__(self, directory):
        self.file_name = os.path.join(directory, "preferences.json")
    
    def set(self, *args):
        """
        Sets a value to a nested dictionary.  For example, 
        user_prefs.set('a', 'b', 'c', 3) is equivalent to
        user_prefs['a']['b']['c'] = 3, except that it also initializes
        user_prefs['a'], user_prefs['a']['b'], and user_prefs['a']['b']['c']
        if needed.
        """
        d = self
        for arg in args[:-2]:
            if not d.has_key(arg):
                d[arg] = {}
            d = d[arg]
        d[args[-2]] = args[-1]

    def load_if_present(self):
        if os.path.exists(self.file_name):
            self.load()
    
    def load(self):
        self.clear()
        with open(self.file_name, "rb") as config_file:
            prefs = json.load(config_file)
            for key, value in prefs.iteritems():
                self[key] = value
    
    def save(self):
        with open(self.file_name, "wb") as config_file:
            json.dump(dict(self), config_file, indent=2)
